package com.ysxn.communicate.socket;

import java.io.IOException;
import java.io.InputStream;

import java.net.Socket;

import com.ysxn.communicate.CommClientInterface;
import org.apache.commons.logging.Log;    
import org.apache.commons.logging.LogFactory;  

/**
 * socket
 *
 * @author Administrator
 *
 */
public class SocketClientThread extends Thread {
    private final Log log = (Log) LogFactory.getLog(SocketClientThread.class);

    private Socket client;
    private InputStream in;
    private CommClientInterface ci = null;
    private int LEN = 1000;
    private byte[] data = new byte[LEN];

    public SocketClientThread(CommClientImpl ci) throws IOException {
        this.ci = ci;
        client = ci.getClient();
        in = client.getInputStream();
        //start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                int count = 0;
                try {
                    if (null == client || client.isClosed()) {
                        return;
                    }
                    count = in.read(data);
                } catch (Exception e1) {
                    return;
                }
                if (count < 0) {
                    Thread.sleep(500);
                    continue;
                }
                int total = 0;
                byte[] td = new byte[10000];
                while (count > -1) {
                    System.arraycopy(data, 0, td, total, count);
                    total += count;
                    if (count < LEN) {
                        count = -1;
                    } else {
                        count = in.read(data);
                    }
                }
                if (total > 0) {
                    ci.onReceived(td, total);
                }

            }
        } catch (Exception e) {
            log.error("received error", e);
        }
    }
}
